package com.ssm.controller;

import com.ssm.po.Product;
import com.ssm.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName: ProductController
 * Package: com.ssm.controller
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/2/11 14:41
 * @Version 1.0
 */

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    ProductService productService;

    @GetMapping("/findAll")
    public String findAll(Model model) {
        List<Product> products = productService.findAll();
        model.addAttribute("products", products);//将products添加到request域
        return "productList";
    }

    @GetMapping("/delete")
    public String delete(Integer pid) {
        productService.deleteByPid(pid);
        return "redirect:/product/findAll";
    }

    /**
     * 跳转到添加商品页面
     * @return
     */
    @GetMapping("addProduct")
    public String addProduct() {
        return "addProduct";
    }

    /**
     * 保存添加的商品信息
     */
    @PostMapping("saveAdd")
    public String saveAdd(Product product) {
        productService.saveProduct(product);
        return "redirect:/product/findAll";
    }


    /**
     * 跳转到更新页面并回显原始的商品数据
     */
    @GetMapping("/updateProduct")
    public String updateProduct(Integer pid, Model model) {
        Product product = productService.findById(pid);
        model.addAttribute("product", product);
        return "editProduct";
    }

    /**
     * 保存更新的商品信息
     */
    @PostMapping("/saveUpdate")
    public String saveUpdate(Product product) {
        productService.updateProduct(product);
        return "redirect:/product/findAll";
    }
}
